<template>
  <div class="carousel">
    <!-- <HeadInfo></HeadInfo> -->
    <main class="main">
      <a-tabs :default-active-key="0" @change="tabsChange">
        <a-tab-pane :tab="ele.site" v-for="ele in tabOptions" :key="ele.id">
          <card-list
            @addNew="addNewCarousel"
            @edit="edit"
            @del="del"
            @imgpreview="imgpreview"
            :loading="loading"
            :carouselList="carouselList"
            :carouselGroupList="carouselGroupList"
            v-if="new Date().getTime()"
          ></card-list>
        </a-tab-pane>
      </a-tabs>
    </main>

    <!-- 创建提示框 -->
    <a-modal
      v-model="visible"
      :title="title"
      ok-text="确认"
      cancel-text="取消"
      @ok="confirm"
      @cancel="cencel"
    >
      <!-- 创建轮播图 -->
      <a-form-model :model="form" ref="ruleForm" v-show="groupSwitch">
        <a-form-model-item label="上传图片" prop="name">
          <a-upload
            name="avatar"
            :headers="headers"
            accept="image/*"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="uploadUrl"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="img" :src="img" alt="avatar" />
            <div v-else>
              <a-icon :type="photoLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="超链接" prop="name">
          <a-input v-model="form.hyperlink" />
        </a-form-model-item>
        <a-form-model-item label="位置" required>
          <a-cascader
            :options="carouselGroupList"
            change-on-select
            placeholder="请选择"
            @change="onChange"
            v-model="groupValue"
          />
          <a-button type="primary" @click="changeGroup">
            创建位置分组
          </a-button>
        </a-form-model-item>
        <a-form-model-item label="排序(数字越小越靠前)">
          <a-input type="number" v-model="form.sort" placeholder="默认999" />
        </a-form-model-item>
      </a-form-model>
      <!-- 创建轮播图分组 -->
      <a-form-model :model="groupForm" ref="ruleForm" v-show="!groupSwitch">
        <a-form-model-item label="轮播图分组" required>
          <a-input v-model="groupForm.site" placeholder="首页-顶部"></a-input>
        </a-form-model-item>
        <a-button type="primary" @click="changeGroup"> 返回轮播图 </a-button>
      </a-form-model>
    </a-modal>

    <!-- 删除提示框 -->
    <a-modal
      v-model="delVisible"
      title="温馨提示"
      ok-text="确认"
      cancel-text="取消"
      @ok="delConfirm"
    >
      是否删除"{{ currentRecord && currentRecord.id }}"轮播图
    </a-modal>
    <!-- 预览框 -->
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="handleCancel"
      :zIndex="1001"
    >
      <img alt="预览图" style="width: 95%" :src="previewsrc" />
    </a-modal>
  </div>
</template>

<script>
import cardList from '@/pages/components/list/cardList';
// import HeadInfo from "@/pages/components/detail/HeadInfo";
import { mapState } from 'vuex';
import {
  getCarousel,
  uploadCarousel,
  updateCarousel,
  deleteCarousel,
  getCarouselGroup,
  addCarouselGroup,
} from '@/services/shopApi/carousel';
import { UPLOAD_CAROUSEL } from '@/services/shopApi/api';
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default {
  name: 'carousel',
  components: {
    cardList,
    // HeadInfo,
  },
  created() {
    this.uploadUrl = UPLOAD_CAROUSEL;
    const userInfo = this.user.user || JSON.parse(localStorage.getItem('user'));
    this.headers['authorization'] = userInfo.token;
    if (!sessionStorage.getItem('carouselList')) {
      this.getCarouselList();
    } else {
      this.carouselList = JSON.parse(sessionStorage.getItem('carouselList'));
    }
    this.getCarouselGroup();
  },
  data() {
    return {
      activeKey: 0,
      groupSwitch: true,
      groupValue: [],
      previewsrc: '',
      previewVisible: false,
      loading: true,
      visible: false,
      delVisible: false,
      imageUrl: '',
      photoLoading: false,
      listBackup: '',
      form: {
        //超链接
        hyperlink: '',
        // 排序
        sort: '',
        // 位置id 1:首页
        site_id: '',
        // 图片id
        photo_id: '',
      },
      groupForm: {
        // 轮播图位置
        project_id: JSON.parse(localStorage.getItem('user')).project_id,
        site: '',
      },
      tabOptions: [
        {
          id: 0,
          site: '全部',
        },
      ],
      carouselGroupList: [],
      // 当前操作行信息
      currentRecord: null,
      uploadUrl: '',
      img: '',
      headers: {},
      title: '',
      carouselList: [],
      desc: '为你的网站添加轮播图吧~',
      extraImage:
        'https://gw.alipayobjects.com/zos/rmsportal/RzwpdLnhmvDJToTdfDPe.png',
    };
  },
  methods: {
    imgpreview(src) {
      this.previewsrc = src;
      this.previewVisible = true;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    tabsChange(activeKey) {
      this.activeKey = activeKey;
      if (activeKey === 0) {
        this.carouselList = this.listBackup;
      } else {
        let site_id = this.tabOptions[activeKey].site_id;
        this.carouselList = this.listBackup.filter((item) => {
          return item.site_id === site_id;
        });
      }
    },
    changeGroup() {
      this.groupSwitch = !this.groupSwitch;
    },
    getCarouselGroup() {
      getCarouselGroup().then((res) => {
        res.result.forEach((item) => {
          this.tabOptions.push({
            id: this.tabOptions.length,
            site: item.site,
            site_id: item.id,
          });

          this.carouselGroupList.push({
            value: item.id,
            label: item.site,
          });
        });
      });
    },
    getCarouselList() {
      const userInfo = JSON.parse(localStorage.getItem('user'));
      getCarousel({ project_id: userInfo.project_id }).then((res) => {
        this.carouselList = res.result;
        this.listBackup = res.result;
        this.loading = false;
      });
    },
    addNewCarousel() {
      this.visible = true;
      if (this.tabOptions.length > 1) {
        this.title = '添加轮播图';
        this.form = {
          //超链接
          hyperlink: '',
          // 排序
          sort: '',
          // 位置id 1:顶部
          site_id: '',
          // 图片id
          photo_id: '',
        };
        this.img = '';
      } else {
        this.title = '添加轮播图分组';
      }
    },
    cencel() {
      setTimeout(() => {
        this.groupSwitch = true;
      }, 500);
    },
    confirm() {
      if (!this.groupSwitch) {
        addCarouselGroup(this.groupForm).then((res) => {
          if (!res.result.id) {
            this.$message.error('创建失败');
            return;
          }
          // 更新选项卡分组数据
          this.tabOptions.push({
            id: this.tabOptions.length,
            site: res.result.site,
            site_id: res.result.id,
          });

          // 更新轮播图分组数据
          this.carouselGroupList.push({
            value: res.result.id,
            label: res.result.site,
          });

          if (this.currentRecord) {
            updateCarousel(this.form)
              .then((res) => {
                this.$message.success(res.msg);
                this.getCarouselList();
              })
              .catch((err) => {
                this.$message.error(err.msg);
              })
              .finally(() => {
                this.groupValue = [];
              });
          }
          // 新增
          else {
            uploadCarousel(this.form)
              .then((res) => {
                this.$message.success(res.msg);
                this.getCarouselList();
              })
              .catch((err) => {
                this.$message.error(err);
              })
              .finally(() => {
                this.groupValue = [];
              });
          }
          this.currentRecord = null;
          this.$message.success('创建成功');
          this.groupForm.site = '';
          setTimeout(() => {
            this.groupSwitch = true;
          }, 500);
        });
      } else {
        if (!this.form.photo_id) {
          this.$message.error('请选择图片');
          return;
        }
        if (!this.form.site_id) {
          this.$message.error('请选择分类');
          return;
        }
        this.visible = false;
        // 编辑更新

        if (this.currentRecord) {
          updateCarousel(this.form)
            .then((res) => {
              this.$message.success(res.msg);
              this.getCarouselList();
            })
            .catch((err) => {
              this.$message.error(err.msg);
            })
            .finally(() => {
              this.groupValue = [];
            });
        }
        // 新增
        else {
          uploadCarousel(this.form)
            .then((res) => {
              this.$message.success(res.msg);
              this.getCarouselList();
            })
            .catch((err) => {
              this.$message.error(err);
            })
            .finally(() => {
              this.groupValue = [];
            });
        }
        this.currentRecord = null;
      }
    },

    onChange(value) {
      this.form.site_id = value[0];
    },

    edit(record) {
      this.visible = true;
      this.title = '编辑轮播图';

      this.form = {
        id: record.id,
        hyperlink: record.hyperlink,
        sort: record.sort,
        photo_id: record.photo_id,
        site_id: record.site_id,
      };

      this.img = record.s_photos[0].path;
      this.currentRecord = record;
    },

    del(record) {
      this.currentRecord = record;
      this.delVisible = true;
    },
    delConfirm() {
      deleteCarousel(this.currentRecord.id)
        .then((res) => {
          this.$message.success(res.msg);
          this.getCarouselList();
          this.delVisible = false;
        })
        .catch((err) => {
          this.$message.error(err.msg);
          this.delVisible = false;
        });
      this.currentRecord = null;
    },

    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.photoLoading = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.form.photo_id = info.file.response.result.id;
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.img = imageUrl;
          this.photoLoading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp' ||
        file.type === 'image/gif' ||
        file.type === 'image/webp';
      if (!isJpgOrPng) {
        this.$message.error('只能上传图片');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB!');
      }
      return isJpgOrPng && isLt2M;
    },

    formDate(path, data) {
      let arr = path.split('');
      let name = '';
      arr.forEach((el) => {
        for (let index = 0; index < data.length; index++) {
          const obj = data[index];
          if (el !== 0 && obj.id == el) {
            name += obj.name + ' -> ';
            break;
          }
        }
      });
      return name;
    },
  },
  computed: {
    ...mapState('account', ['user']),
  },
  watch: {
    /* 重新请求轮播图数据的时候让轮播图渲染列表根据不同分组过滤出来 */
    listBackup: function() {
      if (this.activeKey === 0) {
        this.carouselList = this.listBackup;
      } else {
        let site_id = this.tabOptions[this.activeKey].site_id;
        this.carouselList = this.listBackup.filter((item) => {
          return item.site_id === site_id;
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  background-color: #fff;
  padding: 20px;
}
.adminSetCarousel {
  .ant-btn {
    margin-bottom: 20px;
    margin-right: 20px;
  }
  .ant-table-row img {
    width: 120px;
    height: 120px;
    object-fit: contain;
  }
}
.ant-upload {
  width: 200px !important;
  height: 100px !important;
  img {
    width: 100%;
    height: 100%;
  }
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
